﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    // Animator
    protected Animator anim;

    // 移动
    protected bool dirction = true;
    public Transform ATrans, BTrans;
    protected Vector2 APosition, BPosition;
    protected float speed = 3f;

    // 刚体
    protected Rigidbody2D rb;

    // 碰撞
    public Collider2D coll;

    // 音效
    private AudioSource audioSource;

    // Start is called before the first frame update
    protected virtual void Start()
    {
        anim = GetComponent<Animator>();
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<Collider2D>();
        audioSource = GetComponent<AudioSource>();

        // 记录首次左右移动位置
        APosition = ATrans.position;
        BPosition = BTrans.position;

        // 销毁左右位置物体
        Destroy(ATrans.gameObject);
        Destroy(BTrans.gameObject);
    }

    // 触发Death动画
    public void DeathOn()
    {
        // 启动音效
        audioSource.Play();

        anim.SetTrigger("death");
    }

    // 销毁物体 Animation事件调用
    public void Death()
    {
        Destroy(gameObject);
    }

    // 移动
    public virtual void Movement()
    {
        if (dirction)
        {
            if (transform.position.x < APosition.x)
            {
                dirction = false;
                transform.localScale = new Vector3(-1, 1, 1);
            }

            rb.velocity = new Vector2(-speed, rb.velocity.y);
        }
        else
        {
            if (transform.position.x > BPosition.x)
            {
                dirction = true;
                transform.localScale = new Vector3(1, 1, 1);
            }

            rb.velocity = new Vector2(speed, rb.velocity.y);
        }
    }

    // 禁用Collider和冻结刚体，防止爆炸动画重复触发
    public virtual void ReDeath()
    {
        // 冻结刚体
        rb.constraints = RigidbodyConstraints2D.FreezeAll;

        // 禁用collider
        coll.enabled = false;
    }

    // 碰撞到角色后，切换方向运动
    public virtual void SwitchDirction()
    {
        dirction = !dirction;

        if(dirction)
        {
            LeftDirction();
        }
        else
        {
            RightDirction();
        }

        Movement();
    }

    // 朝向变换
    protected void RightDirction() // 右
    {
        transform.localScale = new Vector3(-1, 1, 1);
    }

    protected void LeftDirction() // 左
    {
        transform.localScale = new Vector3(1, 1, 1);
    }
}
